$(function () {
    $('#saveBtn').css('display', 'none');
    $('#saveForm').css('display', 'none');
    $('#cancelBtn').css('display', 'none');
    $("label[name='delFile']").css('display', 'none');
    $("#files").val("");

    // 编辑器初始化
    var editor = new FroalaEditor('#editor',
        ({
            placeholderText: '',
            charCounterCount: true,//默认 显示字数
            saveInterval: 0,//不自动保存，默认10000，0为不自动保存
            toolbarBottom: false,//默认
            toolbarInline: false,//true选中设置样式,默认false
            imageUploadMethod: 'POST',
            heightMin: 300,
            charCounterMax: 3000,  //最大字数限制，-1为不限制
            saveURL: '/NewsController/addNotify',  //自动保存的地址（body参数为html内容）
            saveParams: {postId: '1'},  //保存内容时传的参数
            spellcheck: false,  //是否允许浏览器对输入内容进行拼写检查
            imageUploadURL: '/file/uploadByOneFile',//上传到本地服务器
            videoUploadURL: '/file/uploadByOneFile',
            language: 'zh_cn'
        }));
    new FroalaEditor('#editor', {toolbarInline: false})
});

// 点击编辑按钮
function editFormFun() {
    $('#saveBtn').css('display', 'block');
    $('#saveForm').css('display', 'block');
    $('#cancelBtn').css('display', 'block');
    $('#editBtn').css('display', 'none');
    $('#editForm').css('display', 'none');
    $("label[name='delFile']").css('display', 'block');
    $('#editor .fr-view').html("");
    $('#editor .fr-view').html($('#notifyContent').text());

    //将新闻详情的附件html赋值给新闻编辑的附件html
    var annexLook = $('#annexLook').html();
    $('#annexEdit').html(annexLook);
}
//保存新闻修改
function saveEditAnnounce() {
    //新闻id
    var notifyId = $("#notifyId").text();

    //新闻标题
    var title = $("#title").val();


    //文本编译器html
    var notifyContent = $('#editor .fr-view').html();

    //获取id为annexEdit编辑模块下的啊标签，将a标签的name添加到一个数组
    var links = $("#annexEdit a");
    var fileIds = [];
    for (var i = 0, j = links.length; i < j; i++) {
        fileIds.push(links[i].name);
    }
    filePaths = fileIds;

    var jsonData = {
        "notifyId": notifyId,
        "title": $.trim(title),
        "notifyContent": notifyContent,
        "fileUrls": filePaths.toString()
    };


    $.ajax({
        url: '/NewsController/updateNotify',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(jsonData),
        success: (function (data) {
            if (data.code == "000000") {
                $.alert("保存成功！");
                setTimeout(function () {
                    $('#editBtn').css('display', 'block');
                    $('#editForm').css('display', 'block');
                    $('#saveBtn').css('display', 'none');
                    $('#saveForm').css('display', 'none');
                    $('#cancelBtn').css('display', 'none');
                    $("label[name='delFile']").css('display', 'none');
                    window.location.href = "/front/newsController/getNotifyDetail?id=" + notifyId;
                }, 3000)

            } else {
                alert("上传失败");
            }
        }),
        error: (function (res) {
            alert("上传失败");
        })
    });
}



//取消编辑新闻
function cancelEditAnnounce() {
    //新闻id
    var notifyId = $("#notifyId").text();
    window.location.href = "/front/newsController/getNotifyDetail?id=" + notifyId;
}


//删除单个文件
function delOneFile(fileId) {
    $.alert({
        title: '提示',
        content: '确定删除吗？',
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary',
                action: function () {
                    //页面移除
                    $("a[name=" + fileId + "]").parent().parent().remove();
                    //删除数据库文件
                    $.ajax({
                        url: '/file/deleteFile',
                        type: 'POST',
                        dataType: "json",
                        contentType: "application/x-www-form-urlencoded",
                        data: {"filePaths": fileId},
                        success: (function (data) {
                            if (data.code == "000000") {
                                console.log("删除文件成功");
                            } else {
                                console.log("删除文件失败");
                            }
                        }),
                        error: (function (res) {
                            console.log("失败");
                        })
                    });
                }
            },
            cancel: {
                text: '取消',
                action: function () {
                }
            }
        }
    });
}



//点击提交按钮
var filePaths = "";
function getUploadFile(ele) {
    //文件选择
    var formData = new FormData();
    var arr = [];
    var container;
    var i = 0;
    //获取选择文件个数
    var files = document.getElementById("files").files;
    if (files.length == 0) {
        //隐藏上传文件进度条
        hideProgress();
    } else {
        //选择文件，上传选择文件
        for (let i = 0; i < files.length; i++) {
            formData.append('files', $(ele)[0].files[i]);
            //console.log(formData.get("files"));
        }
        container = formData.getAll("files");
        for (var item in container) {
            arr[i] = container[item];
            i++;
        }

        //console.log(formData);
        $.ajax({
            url: '/file/upload',
            type: 'POST',
            dataType: "json",
            contentType: false,
            //cache: false,
            //data: JSON.stringify(jsonData),
            data: formData,
            processData: false,
            success: (function (data) {
                if (data.code == "000000") {
                    //进行附件回显
                    var files = [];
                    files = data.data;
                    var html = "";
                    for (let i = 0; i < files.length; i++) {
                        html = html +
                            '<div style="cursor: pointer;">' +
                            '<ul style="margin:0 30px 10px 0;' +
                            '    display: inline-block;\n' +
                            '    min-width: 230px;\n' +
                            '    display: flex;\n' +
                            '    justify-content: space-between;\n' +
                            '    padding: 0;">' +
                            '<li style="display: inline-block;padding-right: 20px;">' +
                            '<a name="' + files[i].uploadId + '" href="' + files[i].accessUrl + '" download="" target="_blank">\n' +
                            '<div style="color: #33cabb;" id="uploadFile' + i + '"> ' + files[i].fileName + ' </div>\n' +
                            '</a>' +
                            '</li>' +
                            ' <li style="display:inline-block;font-size: 12px;color: #ccc;">' +
                            '<label name="delFile"  onclick="delOneFile(\'' + files[i].uploadId + '\')">删除</label>' +
                            '</li>' +
                            '</div>';
                    }

                    $('#annexEdit').html($('#annexEdit').html()+html);
                    //上传文件的选择文件置为空
                    //$("#files").val("");
                } /*else {
                    alert("上传失败");
                }*/
            }),
            error: (function (res) {
                alert("失败");
            }),
            xhr: function () {
                var xhr = $.ajaxSettings.xhr();
                if (xhr.upload) {
                    //处理进度条的事件
                    xhr.upload.addEventListener("progress", progressHandle, false);
                    //加载完成的事件
                    xhr.addEventListener("load", completeHandle, false);
                    //加载出错的事件
                    xhr.addEventListener("error", failedHandle, false);
                    //加载取消的事件
                    xhr.addEventListener("abort", canceledHandle, false);
                    //开始显示进度条

                    showProgress();
                    return xhr;
                }
            }
        });
    }
}

//显示进度条的函数
function showProgress() {
    start = new Date().getTime();
    $(".progress-body").css("display", "block");
}

//隐藏进度条的函数
function hideProgress() {
    $('.progress-body percentage').html("0%");
    $(".progress-body").css("display", "none");
}

//进度条更新
function progressHandle(e) {
    $('.progress-body progress').attr({value: e.loaded, max: e.total});
    var percent = e.loaded / e.total * 100;
    $('.progress-body percentage').html(percent.toFixed(2) + "%");
    if (percent == 100) {
        $('.progress-body .progress-info').html("上传完成,后台正在处理...");
    } else {
        $('.progress-body .progress-info').html("文件上传中...");
    }
}
//上传完成处理函数
function completeHandle(e) {
    $('.progress-body .progress-info').html("上传文件完成。");
    //setTimeout(hideProgress, 2000);
}
//上传出错处理函数
function failedHandle(e) {
    $('.progress-body .progress-info').html("上传文件出错, 服务不可用或文件过大。");
    // setTimeout(hideProgress, 2000);
}
//上传取消处理函数
function canceledHandle(e) {
    $('.progress-body .progress-info').html("上传文件取消。");
    //setTimeout(hideProgress, 2000);
}
function saveAddNotify() {

    //新闻标题
    var title = $("#title").val();

    //文本编译器html
    var notifyContent = $('#editor .fr-view').html();

    //新闻标题为空和长度验证
    if (!title) {
        ok = false;
        promptInfo("新闻标题不能为空!");
        return;
    } else {
        if (title.length > 30) {
            ok = false;
            promptInfo("新闻标题长度不能大于30个字！");
            return;
        }
    }


    //附件idList
    var links = $("#annexEdit a");

    var fileIds = [];

    for (var i = 0, j = links.length; i < j; i++) {
        fileIds.push(links[i].name);
    }
    filePaths = fileIds;

    var jsonData = {
        "title": $.trim(title),
        "notifyContent": notifyContent,
        "fileUrls": filePaths.toString()
    };

    $.ajax({
        url: '/NewsController/addNotify',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(jsonData),
        success: (function (data) {
            if (data.code == "000000") {
                $.alert("保存成功！");
                setTimeout(function () {
                    $('#editBtn').css('display', 'block');
                    $('#editForm').css('display', 'block');
                    $('#saveBtn').css('display', 'none');
                    $('#saveForm').css('display', 'none');
                    var $thisTabs = parent.$('.mt-nav-bar .nav-tabs').find('li.active');
                    var navTab = parent.$multitabs._getNavTab($thisTabs);
                    //关闭当前页签
                    closeTab(navTab);
                    //打开首页
                    openTab("首页","main");
                    delStorageAndRemove(navTab);
                }, 3000)

            } else {
                alert("上传失败");
            }
        }),
        error: (function (res) {
            alert("失败");
        })
    });
}

function promptInfo(content) {
    $.alert({
        title: '温馨提示',
        content: content,
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary'
            }
        }
    });
}

function cancelAddAnnounce() {

    //附件idList
    var links = $("#annexEdit a");

    var fileIds = [];

    for (var i = 0, j = links.length; i < j; i++) {
        fileIds.push(links[i].name);
    }
    filePaths = fileIds;

    //获取选择文件个数
    var files = document.getElementById("files").files;
    if (files.length != 0) {
        //如果选择文件，就把选择的文件进行删除
        $.ajax({
            url: '/file/deleteFile',
            type: 'POST',
            dataType: "json",
            contentType: "application/x-www-form-urlencoded",
            data: {"filePaths": filePaths.toString()},
            success: (function (data) {
                if (data.code == "000000") {
                    console.log("删除文件成功");
                } else {
                    console.log("删除文件失败");
                }
            }),
            error: (function (res) {
                console.log("失败");
            })
        });
    }

    //关闭当前页签
    var $thisTabs = parent.$('.mt-nav-bar .nav-tabs').find('li.active');
    var $navTab = parent.$multitabs._getNavTab($thisTabs);
    parent.$multitabs.close($navTab);
}